<?php
namespace Anls\Com\Indicator;

/**
 * Ma移动平均线
 * @author w.
 *
 */
class MA extends AbstractIndicatorSupport {

    const KEY = 'MA';
	
    /**
     * 表达式计算
     * 
     * @param array $bar
     * @param string $key
     * @param bar下标 $shift
     */
    public static function calcExpr($bar,$key,$shift){
        $sum = 0;
        $value = -1;
        $period = explode("_", $key)[1];
        if($shift < ($period - 1)) 
            return $value;
        for($n=$shift;$n>=$shift-$period+1;$n--){
            $sum += $bar[$n]['close'];
        }
        $value = round($sum/$period,2);
        return $value;    
    }
        
    /**
     * 计算
     * 
     * @param array $bar
     * @param int $period
     */
	public static function calc(&$bar,$period){
		$sum = 0;
		$cnt = count($bar)-1;
		for($i=$cnt;$i>=$period-1;$i--){   
			$sum = 0;
			for($n=$i;$n>=$i-$period+1;$n--){
				$sum += $bar[$n]['close'];
			}
			$bar[$i][self::getKey($period)] = round($sum/$period,2);
		}
	   	return $bar;
	}

	public static function getKey($period){
	    return self::KEY.'_'.$period;
	}
	
	public static function matchKey($key){
	    return strpos($key,self::KEY);
	}
}

?>
